const api = require('../../../utils/api')

Page({
  data: {
    currentStatus: '', // 当前选中的状态
    orders: [], // 订单列表
    page: 1, // 当前页码
    size: 10, // 每页数量
    hasMore: true, // 是否还有更多数据
    loading: false, // 是否正在加载
    tabList: [
      { id: 'all', name: '全部' },
      { id: '1', name: '待付款' },
      { id: '2', name: '待发货' },
      { id: '3', name: '已发货' },
      { id: '4', name: '已完成' },
      { id: '5', name: '已取消' }
    ],
    activeTab: 'all'
  },

  onLoad() {
    this.loadOrders()
  },

  onShow() {
    // 每次显示页面时重新加载订单
    this.setData({
      orders: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadOrders()
    })
  },

  onPullDownRefresh() {
    this.setData({
      orders: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadOrders().then(() => {
        wx.stopPullDownRefresh()
      })
    })
  },

  // 切换订单状态
  handleTabChange(e) {
    const { id } = e.currentTarget.dataset
    this.setData({
      activeTab: id,
      orders: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadOrders()
    })
  },

  // 加载订单列表
  async loadOrders() {
    if (this.data.loading || !this.data.hasMore) return

    try {
      this.setData({ loading: true })

      const params = {
        page: this.data.page - 1,
        size: this.data.size
      }

      let res;
      if (this.data.activeTab === 'all') {
        res = await api.getMerchantOrders(undefined, params);
      } else {
        res = await api.getMerchantOrders(parseInt(this.data.activeTab), params);
      }

      if (res.success) {
        const { content, last } = res.data
        
        // 处理订单数据
        const processedOrders = content.map(order => ({
          ...order,
          statusText: this.getStatusText(order.status)
        }))

        this.setData({
          orders: [...this.data.orders, ...processedOrders],
          page: this.data.page + 1,
          hasMore: !last
        })
      } else {
        wx.showToast({
          title: res.message || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载订单列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 获取订单状态文本
  getStatusText(status) {
    const statusMap = {
      1: '待付款',
      2: '待发货',
      3: '已发货',
      4: '已完成',
      5: '已取消'
    }
    return statusMap[status] || '未知状态'
  },

  // 查看订单详情
  viewDetail(e) {
    const { orderNo } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/admin/order/detail?orderNo=${orderNo}`
    })
  },

  // 发货
  async handleShip(e) {
    const { orderNo } = e.currentTarget.dataset
    
    try {
      wx.showModal({
        title: '发货确认',
        content: '确认发货吗？',
        success: async (res) => {
          if (res.confirm) {
            const result = await api.updateMerchantOrderStatus(orderNo, 3, '商家已发货')
            if (result.success) {
              wx.showToast({
                title: '发货成功',
                icon: 'success'
              })
              // 重新加载订单列表
              this.setData({
                orders: [],
                page: 1,
                hasMore: true
              }, () => {
                this.loadOrders()
              })
            } else {
              wx.showToast({
                title: result.message || '发货失败',
                icon: 'none'
              })
            }
          }
        }
      })
    } catch (error) {
      console.error('发货失败:', error)
      wx.showToast({
        title: error.message || '发货失败',
        icon: 'none'
      })
    }
  },
  
  // 删除订单
  async handleDelete(e) {
    const { orderNo } = e.currentTarget.dataset
    
    try {
      wx.showModal({
        title: '删除确认',
        content: '确认删除此订单吗？此操作不可撤销。',
        success: async (res) => {
          if (res.confirm) {
            const result = await api.deleteMerchantOrder(orderNo)
            if (result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              // 重新加载订单列表
              this.setData({
                orders: [],
                page: 1,
                hasMore: true
              }, () => {
                this.loadOrders()
              })
            } else {
              wx.showToast({
                title: result.message || '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    } catch (error) {
      console.error('删除订单失败:', error)
      wx.showToast({
        title: error.message || '删除失败',
        icon: 'none'
      })
    }
  }
}) 